import { Button, Space } from "@douyinfe/semi-ui";
import React, { useState } from "react";

const HttpCache: React.FC = () => {
  const [count, setCount] = useState(1);

  /**
   * cache-control测试
   */
  const getCacheControl = async () => {
    const res = await fetch("http://localhost:3002/cache-control");
    const data = await res.json();
    console.log(data);
  };

  /**
   * expires测试
   */
  const getExpires = async () => {
    const res = await fetch("http://localhost:3002/expires");
    const data = await res.json();
    console.log(data);
  };

  /**
   * last-modified&if-modified-since测试
   * Last-modified: 服务器上次修改时间
   */
  const getLastModified = async () => {
    const res = await fetch("http://localhost:3002/last-modified");
    const data = await res.json();
    console.log(data);
  };

  const handleStartWorker = () => {
    // 创建worker实例
    const worker = new Worker("./work.ts");

    // 监听消息事件
    worker.onmessage = function (event) {
      setCount(event.data);
      worker.terminate(); // 终止worker实例
    };

    // 向Web Worker发送消息
    worker.postMessage(count);
  };

  return (
    <>
      <h3>Http设置缓存的四种方式</h3>
      <Space wrap>
        <Button onClick={getCacheControl}>Cache-control测试</Button>
        <Button onClick={getExpires}>Expires测试</Button>
        <Button onClick={getLastModified}>Last-modified&if-modified-since测试</Button>
        <Button>Etag&if-None-Match测试</Button>
        <Button onClick={handleStartWorker}>测试web worker</Button>
        <h4>Count:{count}</h4>
      </Space>
    </>
  );
};

export default HttpCache;
